#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define BUFSIZE 256

	static int pos_(char *buff,int len,int line)
{
	int i,flag = 0;
	for(i = 0;i < len;i++)
	{
		if(buff[i] == '\n')
		{
			flag++;
		}
		if(flag == line)
		{
			return i++;
		}
	}
}

/*功能:删除文件的第n行
 *
 *
 */

int main(int argc,char **argv)
{
	if(argc < 2)
	{
		fprintf(stderr,"Usage:%s",argv[0]);
		exit(1);
	}
	int fps,fpd;
	char buf[BUFSIZE] = {0};
	int pos = 0,ret = 0;
	int i,n,len = 0;
	int trunlen = 0,l1,l2;
	printf("Please Input delete line:\n");
	scanf("%d",&n);

	fps = open(argv[1],O_RDONLY);
	fpd = open(argv[1],O_RDWR);

	read(fps,buf,BUFSIZE);
	len = strlen(buf);
	
	l1 = lseek(fps,pos_(buf,len,n),SEEK_SET);
	l2 = lseek(fpd,pos_(buf,len,n-1),SEEK_SET);
	trunlen = len-(l1-l2);
	while(1)
	{
		len = read(fps,buf,BUFSIZE);
		if(len < 0)
		{
			perror("read()");
			exit(1);
		}
		if(len == 0)
		{
			break;
		}
		while(len > 0)
		{
			ret = write(fpd,buf+pos,len);
			if(ret < 0)
			{
				perror("write()");
				exit(1);
			}
			len -= ret;
			pos += ret;
		}
	}
	ftruncate(fpd,trunlen);	
	close(fps);
	close(fpd);

	exit(0);
}
